package cn.boot.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.boot.common.BaseAction;
import cn.boot.entity.Draft;
import cn.boot.service.BizService;
import mailclient.object.FileObject;
import mailclient.object.Mail;
import mailclient.system.MainFrame;
import mailclient.util.FileUtil;
import util.Constant;
import util.DateUtil;
import util.MessageUtil;

@Controller
@RequestMapping("/sys")
public class MailAction extends BaseAction {
	@Autowired
	private BizService service;

	//去写信
	@RequestMapping(value = "/xie.do")
	public String add2() {
		List<?> list = service.queryByHQL("from Contact where user.id=?", getSimpleUser().getId());
		putRequestValue("clist", list);
		return "xie";
	}

	//接收邮件
	@RequestMapping(value = "/shou.do")
	public String shou() {
		MainFrame mailbean = getMailContextBean();
		mailbean.receive();

		putRequestValue("list", mailbean.inMails);
		return "shou";
	}

	//读取收件
	@RequestMapping(value = "/du.do")
	public String du() {
		String uuid = getString("uuid") + ".xml";
		MainFrame mailbean = getMailContextBean();
		Mail current = null;
		String f = getString("f");
		List<Mail> mlist = null;
		if ("laji".equals(f)) {
			mlist = mailbean.spamMails;
		} else {
			mlist = mailbean.inMails;
		}
		for (Mail m : mlist) {
			if (m.getXmlName().equals(uuid)) {
				current = m;
				break;
			}
		}
		putRequestValue("modifybean", current);
		putRequestValue("f", f);
		return "du";
	}

	//读取已发收件
	@RequestMapping(value = "/duYiFa.do")
	public String duYiFa() {
		String uuid = getString("uuid") + ".xml";
		MainFrame mailbean = getMailContextBean();
		Mail current = null;
		for (Mail m : mailbean.sentMails) {
			if (m.getXmlName().equals(uuid)) {
				current = m;
				break;
			}
		}
		putRequestValue("modifybean", current);
		return "duYiFa";
	}

	//读取已删收件
	@RequestMapping(value = "/duYiShan.do")
	public String duYiShan() {
		String uuid = getString("uuid") + ".xml";
		MainFrame mailbean = getMailContextBean();
		Mail current = null;
		for (Mail m : mailbean.deleteMails) {
			if (m.getXmlName().equals(uuid)) {
				current = m;
				break;
			}
		}
		putRequestValue("modifybean", current);
		return "duYiShan";
	}

	//去回复
	@RequestMapping(value = "/hui.do")
	public String hui() {
		String uuid = getString("uuid") + ".xml";
		MainFrame mailbean = getMailContextBean();
		Mail current = null;
		String f = getString("f");
		List<Mail> mlist = null;
		if ("laji".equals(f)) {
			mlist = mailbean.spamMails;
		} else {
			mlist = mailbean.inMails;
		}
		for (Mail m : mlist) {
			if (m.getXmlName().equals(uuid)) {
				current = m;
				break;
			}
		}
		String sender = current.getSender();
		sender = getRealAddress(sender);

		putRequestValue("sender", sender);
		putRequestValue("modifybean", current);
		return "huifu";
	}

	//回信
	@RequestMapping(value = "/huiXin.do")
	public String huiXin() {
		try {
			MainFrame mailbean = getMailContextBean();
			String receiver = getString("to");
			String subject = getString("title");
			String content = getString("content");
			String file = getString("upload");
			if (StringUtils.isNotBlank(file)) {
				file = getResourceFile() + File.separator + file;
			}
			log.info(file);
			String xmlName = UUID.randomUUID().toString() + ".xml";
			Mail mail = new Mail(xmlName, getAddressList(receiver), mailbean.getMailContext().getAccount(), subject, new Date(), "10", true, content,
					FileUtil.SENT);
			mail.setCcs(new ArrayList<String>());
			//mail.setCcs(getAddressList(this.cc));
			List<FileObject> files = new ArrayList<FileObject>();
			if (StringUtils.isNotBlank(file)) {
				FileObject fo = new FileObject();
				fo.setFile(new File(file));
				fo.setSourceName(fo.getFile().getName());
				files.add(fo);
			}
			mail.setFiles(files);

			mailbean.getMailSender().send(mail, mailbean.getMailContext());
			//将Mail对象保存到发送成功的目录(sent)

			mailbean.getSystemHandler().saveSent(mail, mailbean.getMailContext());
			//添加了已发送的集合中
			mailbean.addSentMail(mail);

			MessageUtil.addCloseMessage(getHttpServletRequest(), "邮件已发送", "xie");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(getHttpServletRequest(), "发送失败");
			return ERROR;
		}

	}

	//下载附件
	@RequestMapping(value = "/fujian.do")
	public String fujian() {
		try {
			String uuid = getString("uuid") + ".xml";
			String rel = getString("rel");
			MainFrame mailbean = getMailContextBean();
			Mail current = null;
			List<Mail> list = null;
			if ("shou".equals(rel)) {
				list = mailbean.inMails;
			} else if ("fa".equals(rel)) {
				list = mailbean.sentMails;
			} else if ("shan".equals(rel)) {
				list = mailbean.deleteMails;
			}
			for (Mail m : list) {
				if (m.getXmlName().equals(uuid)) {
					current = m;
					break;
				}
			}
			int index = getInt("index");
			FileObject fo = current.getFiles().get(index);
			String file = fo.getFile().getAbsolutePath();
			cn.boot.action.FileUtil.download(getHttpServletRequest(), getHttpServletResponse(), file, Constant.CONTENTTYPE_OCTET_STREAM,
					fo.getSourceName());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	//写信
	@RequestMapping(value = "/xieXin.do")
	public String xieXin() {
		try {
			String caogao = getString("caogao");
			String receiver = getString("to");
			String subject = getString("title");
			String content = getString("content");
			String file = getString("upload");
			if ("是".equals(caogao)) {
				Draft d = new Draft();
				d.setUser(getSimpleUser());
				d.setAddDate(DateUtil.getCurrentTime(DateUtil.FULL));
				d.setContent(content);
				d.setSendTo(receiver);
				if (StringUtils.isNotBlank(file)) {
					//file = getResourceFile() + File.separator + file;
					d.setFujian(file);
					d.setFujianMing(file);
				}
				d.setTitle(subject);
				service.add(d);
				MessageUtil.addRelMessage(getHttpServletRequest(), "邮件已存草稿", "xie");
				return SUCCESS;
			}

			MainFrame mailbean = getMailContextBean();

			if (StringUtils.isNotBlank(file)) {
				file = getResourceFile() + File.separator + file;
			}
			log.info(file);
			String xmlName = UUID.randomUUID().toString() + ".xml";
			Mail mail = new Mail(xmlName, getAddressList(receiver), mailbean.getMailContext().getAccount(), subject, new Date(), "10", true, content,
					FileUtil.SENT);
			List<String> templist = new ArrayList<String>();
			templist.add(mailbean.getMailContext().getAccount());
			mail.setCcs(templist);
			//mail.setCcs(getAddressList(this.cc));
			List<FileObject> files = new ArrayList<FileObject>();
			if (StringUtils.isNotBlank(file)) {
				FileObject fo = new FileObject();
				fo.setFile(new File(file));
				fo.setSourceName(fo.getFile().getName());
				files.add(fo);
			}
			mail.setFiles(files);

			mailbean.getMailSender().send(mail, mailbean.getMailContext());
			//将Mail对象保存到发送成功的目录(sent)

			mailbean.getSystemHandler().saveSent(mail, mailbean.getMailContext());
			//添加了已发送的集合中
			mailbean.addSentMail(mail);

			MessageUtil.addRelMessage(getHttpServletRequest(), "邮件已发送", "xie");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(getHttpServletRequest(), "操作失败:");
			return ERROR;
		}
	}

	//删除邮件
	@RequestMapping(value = "/shan.do")
	public String shan() {
		try {
			String ids = getString("ids");
			String rel = getString("rel");
			log.info(ids);
			String[] ary = ids.split(",");
			MainFrame mailbean = getMailContextBean();
			for (String uuid : ary) {
				uuid = uuid + ".xml";
				Mail current = null;
				List<Mail> list = null;
				if ("shou".equals(rel)) {
					list = mailbean.inMails;
				} else if ("yiFa".equals(rel)) {
					list = mailbean.sentMails;
				} else if ("yishan".equals(rel)) {
					list = mailbean.deleteMails;
				} else if ("laji".equals(rel)) {
					list = mailbean.spamMails;
				}
				for (Mail m : list) {
					if (m.getXmlName().equals(uuid)) {
						current = m;
						break;
					}
				}
				//log.info(current.getFrom());
				list.remove(current);
				if ("yiFa".equals(rel) && !mailbean.deleteMails.contains(current)) {
					//从当前的集合中删除
					//mailbean.currentMails.remove(current);
					//加到垃圾箱的集合中
					mailbean.deleteMails.add(0, current);
					//将邮件对应的xml文件放到deleted的目录中
					mailbean.getSystemHandler().delete(current, mailbean.getMailContext());
				}else{
					mailbean.getSystemHandler().realDelete(current, mailbean.getMailContext());
				}
			}
			MessageUtil.addRelMessage(getHttpServletRequest(), "删除成功", rel);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(getHttpServletRequest(), "删除失败");
			return ERROR;
		}

	}

	//恢复邮件
	@RequestMapping(value = "/huifu.do")
	public String huifu() {
		try {
			String ids = getString("ids");
			String rel = getString("rel");
			log.info(ids);
			String[] ary = ids.split(",");
			MainFrame mailbean = getMailContextBean();
			for (String uuid : ary) {
				uuid = uuid + ".xml";
				Mail current = null;
				List<Mail> list = mailbean.deleteMails;

				for (Mail m : list) {
					if (m.getXmlName().equals(uuid)) {
						current = m;
						break;
					}
				}
				//log.info(current.getFrom());
				list.remove(current);
				if ("inbox".equalsIgnoreCase(current.getFrom())) {
					mailbean.inMails.add(0, current);
				} else if ("sent".equalsIgnoreCase(current.getFrom())) {
					mailbean.sentMails.add(0, current);
				} else if ("spam".equalsIgnoreCase(current.getFrom())) {
					mailbean.spamMails.add(0, current);
				}
			}
			MessageUtil.addRelMessage(getHttpServletRequest(), "恢复成功", rel);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(getHttpServletRequest(), "恢复失败");
			return ERROR;
		}

	}

	/**
	 * 已发送邮件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/yiFa.do")
	public String yiFa() {
		MainFrame mailbean = getMailContextBean();
		putRequestValue("list", mailbean.sentMails);
		return "yiFa";
	}

	/**
	 * 已删除邮件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/yiShan.do")
	public String yiShan() {
		MainFrame mailbean = getMailContextBean();
		putRequestValue("list", mailbean.deleteMails);
		return "yiShan";
	}

	/**
	 * 垃圾邮件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/laji.do")
	public String laji() {
		MainFrame mailbean = getMailContextBean();
		putRequestValue("list", mailbean.spamMails);
		return "laji";
	}

	private List<String> getAddressList(String all) {
		List<String> result = new ArrayList<String>();
		if (all.equals(""))
			return result;
		for (String re : all.split(",")) {
			result.add(re);
		}
		return result;
	}

	private String getRealAddress(String toname) {
		int start = 0;
		int end = toname.length();
		if (toname.indexOf("<") > 0) {
			start = toname.indexOf("<");
		}
		if (toname.indexOf(">") > 0) {
			end = toname.indexOf(">");
		}
		if (start > 0) {
			start = start + 1;
		}
		toname = toname.substring(start, end);
		return toname;
	}

}
